package fr.sedoo.metadata.client.ui.widget.field.primitive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBoxBase;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.commons.client.util.LocaleUtil;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.metadata.client.ui.widget.field.api.IsDisplay;
import fr.sedoo.metadata.client.ui.widget.field.api.IsEditor;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.shared.domain.misc.Iso6392LanguageProvider;

public abstract class I18nField extends HorizontalPanel implements IsDisplay, IsEditor {
	protected Label label;
	protected TabPanel editPanel;
	protected List<String> languages;
	protected HashMap<String, TextBoxBase> editors = new HashMap<String, TextBoxBase>();

	public I18nField(ArrayList<String> languages) {
		super();
		this.languages = languages;
		setWidth(FieldConstant.HUNDRED_PERCENT);
		label = new Label();
		ElementUtil.hide(label);
		add(label);
		editPanel = new TabPanel();
		editPanel.setWidth("100%");
		add(editPanel);
		ElementUtil.hide(editPanel);
	}

	protected abstract TextBoxBase createEditor();

	public void display(String text) {
		ElementUtil.show(label);
		ElementUtil.hide(editPanel);
		label.setText(StringUtil.trimToEmpty(text));
	}

	@Override
	public void reset() {
		label.setText("");
		editors.clear();
		editPanel.clear();
	}

	protected HashMap<String, String> getI18nValues() {
		HashMap<String, String> i18nValues = new HashMap<String, String>();
		Iterator<String> iterator = editors.keySet().iterator();
		while (iterator.hasNext()) {
			String language = iterator.next();
			i18nValues.put(language, StringUtil.trimToEmpty(editors.get(language).getText()));
		}
		return i18nValues;
	}

	public void edit(HashMap<String, String> i18nValues) {
		ElementUtil.hide(label);
		ElementUtil.show(editPanel);
		editors.clear();
		editPanel.clear();
		Iterator<String> iterator = languages.iterator();
		while (iterator.hasNext()) {
			String language = (String) iterator.next();
			TextBoxBase editor = createEditor();
			editor.setText(StringUtil.trimToEmpty(i18nValues.get(language)));
			editors.put(language, editor);
			String locale = Iso6392LanguageProvider.convertIso6392Tolocale(language);
			HorizontalPanel aux = new HorizontalPanel();
			aux.add(editor);
			editPanel.add(aux, LocaleUtil.getLanguageFlag(locale));
		}
		editPanel.selectTab(0);

	}
}
